package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import com.qf.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;


import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User selectUserByName(String username) throws SQLException {
        QueryRunner queryRunner = new QueryRunner ( JdbcUtils.getDataSource ( ) );
        String sql = "select * from user where username=?";
        User user = queryRunner.query ( sql , new BeanHandler<User> ( User.class ) , username );
        return user;

    }

    @Override
    public void updateUser(User user) throws SQLException {
        QueryRunner queryRunner = new QueryRunner ( JdbcUtils.getDataSource ( ) );
        String sql = "update user set  username = ?,password=?,name =?,email=?,telephone=?,birthday=?,sex=?,state=?,code=? where uid  =?";
        int count = queryRunner.update ( sql ,
                user.getUsername ( ) ,
                user.getPassword ( ) ,
                user.getName ( ) ,
                user.getEmail ( ) ,
                user.getTelephone ( ) ,
                user.getBirthday ( ) ,
                user.getSex ( ) ,
                user.getState ( ) ,
                user.getCode ( ) ,
                user.getUid ( ) );
        System.out.println ( count );
    }

    @Override
    public void addUserSelect(User user) throws SQLException {
        //创建执行对象
        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()) ;

        //sql

        String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)" ;

        //更新
        int count = qr.update(sql,
                user.getUid(),
                user.getUsername(),
                user.getPassword(),
                user.getName(),
                user.getEmail(),
                user.getTelephone(),
                user.getBirthday(),
                user.getSex(),
                user.getState(),
                user.getCode()
        );
    }

    @Override
    public User getUserByCodeSelect(String code) throws SQLException {
        QueryRunner queryRunner = new QueryRunner ( JdbcUtils.getDataSource ( ) );
        String sql = "select * from user where code = ?";
        User user = queryRunner.query ( sql , new BeanHandler<User> ( User.class ) , code );
        return user;


    }

    @Override
    public User findUserByNameAndPassword(String username , String password) throws SQLException {
        QueryRunner queryRunner = new QueryRunner ( JdbcUtils.getDataSource () );

        String sql = "select * from user where username=? and password=?";

        User user = queryRunner.query ( sql , new BeanHandler<User> ( User.class ) , username , password );
        return user;

    }
}